using Microsoft.AspNetCore.Mvc;
using ERPBackend.Models;
using ERPBackend.Services;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ERPBackend.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RolesController : ControllerBase
    {
        private readonly IRoleService _roleService;

        public RolesController(IRoleService roleService)
        {
            _roleService = roleService;
        }

        // GET: api/Roles
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Role>>> GetRoles()
        {
            var roles = await _roleService.GetAllRolesAsync();
            return Ok(roles);
        }

        // GET: api/Roles/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Role>> GetRole(int id)
        {
            var role = await _roleService.GetRoleByIdAsync(id);

            if (role == null)
            {
                return NotFound();
            }

            return Ok(role);
        }

        // PUT: api/Roles/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutRole(int id, Role role)
        {
            if (id != role.Id)
            {
                return BadRequest();
            }

            var updatedRole = await _roleService.UpdateRoleAsync(role);

            if (updatedRole == null)
            {
                return NotFound();
            }

            return NoContent();
        }

        // POST: api/Roles
        [HttpPost]
        public async Task<ActionResult<Role>> PostRole(Role role)
        {
            var createdRole = await _roleService.CreateRoleAsync(role);

            return CreatedAtAction("GetRole", new { id = createdRole.Id }, createdRole);
        }

        // DELETE: api/Roles/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteRole(int id)
        {
            var result = await _roleService.DeleteRoleAsync(id);

            if (!result)
            {
                return NotFound();
            }

            return NoContent();
        }

        // GET: api/Roles/5/permissions
        [HttpGet("{id}/permissions")]
        public async Task<ActionResult<IEnumerable<RolePermission>>> GetRolePermissions(int id)
        {
            var permissions = await _roleService.GetRolePermissionsAsync(id);
            return Ok(permissions);
        }

        // POST: api/Roles/5/permissions
        [HttpPost("{id}/permissions")]
        public async Task<IActionResult> PostRolePermissions(int id, [FromBody] List<int> permissionIds)
        {
            var result = await _roleService.UpdateRolePermissionsAsync(id, permissionIds);

            if (!result)
            {
                return NotFound();
            }

            return NoContent();
        }
    }
}